<?php

class EventsController extends AppController {
	var $name = 'Events';
	var $helpers = array('Html','Form','Accessibility','Pagination', 'Associations', 'Ajax', 'Input', 'Calendar');
	var $components = array('Domini');
	var $uses = array('Event', 'Calendar','Volunteer', 'Employee', 'Assistido');
	
	function index() {
		$title = 'Eventos';
		$this->set('title', $title);
		$this->set('pageTitle', $title);

		$conditions = array();
		// Permissao: se pode visualizar todas as unidades
		$group = $this->othAuth->getData('group');
		$level =$group['level'];
		$unitUser = $this->othAuth->getData('unit');

		if ($level >= 100) {  // not system admin
			$conditions[] = array("`Event`.organization_id"=>$unitUser['0']['Organization']['id']);
		}

		$events = $this->Event->find('all',array("conditions"=>$conditions));
		$this->set('events', $events);
	}

	function view( $id=null ) {
		if (!$id) $this->redirect('/events');
		$title = 'Visualizar evento';
		$this->set('title', $title);
		$this->set('pageTitle', $title);

		$this->Event->id = $id;
		$this->set('event', $this->Event->read());
	}

	function calendar($calendar=null,$tag=null,$date=null) {
		$title = 'Eventos';
		$this->set('title', $title);
		$this->set('pageTitle', $title);
		
		// Permissao: se pode visualizar todas as unidades
		$group = $this->othAuth->getData('group');
		$level =$group['level'];
		$unitUser = $this->othAuth->getData('unit');
		$conditions = array();
		$organization_id = null;
		if ($level >= 100) {  // not system admin
			$organization_id = $unitUser['0']['Organization']['id'];
		}
		
		// Recupera informacoes
		$data = $this->Domini->parseUrl($calendar,$tag,$date);
		$prev = $this->Domini->findPrev($this->params['pass']);
		$next = $this->Domini->findNext($this->params['pass']);

		$events = $this->Event->findEvents($data,$organization_id);
		$data['calendar_name'] = $this->requestAction('/calendars/findNameByShortname/'.$calendar);
		$data['tag_name'] = $this->requestAction('/tags/findNameByShortname/'.$tag);
		$birthdays = array();
		if ($data['calendar'] == 'all') { /* Exibir os aniversarios */
			
			$month = $data['month'];
			
			// Permissao: se pode visualizar todas as unidades
			$group = $this->othAuth->getData('group');
			$level =$group['level'];
			$unitUser = $this->othAuth->getData('unit');
	
			// Filter for present only employee from an organization
			$where = '';
			if ($level < 100) {  // system admin
				$where .= '';
			} else {
				$where .= ' AND Unit.organization_id ='.$organization_id;
			}
					
			// Buscando voluntarios
			// Filter for present only volunteer from an organization
			$volunteers = $this->Volunteer->query(
				'SELECT DISTINCT Volunteer.id, User.name, User.id, User.birthdate'.
				' FROM volunteers as Volunteer'.
				' INNER JOIN users as User ON Volunteer.user_id = User.id'.
				' INNER JOIN units_users as UnitUser ON User.id = UnitUser.user_id'.
				' INNER JOIN units as Unit ON UnitUser.unit_id = Unit.id'.
				' WHERE 1 = 1 '.$where.' AND MONTH(`User`.birthdate) = '.$month
			);
			$volunteers_count = count($volunteers);
			for ($i=0; $i<$volunteers_count; $i++) {
				if (isset($volunteers[$i]['User'])) {
					$user = $this->Volunteer->User->findById($volunteers[$i]['User']['id']);
	
					$volunteers[$i]['User'] = $user['User'];
					$volunteers[$i]['User']['Unit'] = $user['Unit'];
					$volunteers[$i]['User']['Group'] = $user['Group'];
				}
			}
	
			// Copia as informacoes de aniversario
			foreach ($volunteers as $volunteer) {
				$entry = array();
				$entry['type'] = "volunteer";
				$entry['date'] = $volunteer['User']['birthdate'];
				$entry['id'] = $volunteer['Volunteer']['id'];
				$name = $volunteer['User']['name'];
				$entry['name'] = $name;
				$entry['nick'] = substr($name, 0, strpos($name,' '));
				$birthdays[]=$entry;
			}
			
			// Buscando funcionarios
			// Filter for present only employee from an organization
			$employees = $this->Employee->query(
				'SELECT DISTINCT Employee.id, User.name, User.id, User.birthdate'.
				' FROM employees as Employee'.
				' INNER JOIN users as User ON Employee.user_id = User.id'.
				' INNER JOIN units_users as UnitUser ON User.id = UnitUser.user_id'.
				' INNER JOIN units as Unit ON UnitUser.unit_id = Unit.id'.
				' WHERE 1 = 1 '.$where.' AND MONTH(`User`.birthdate) = '.$month
			);
			$employees_count = count($employees);
			for ($i=0; $i<$employees_count; $i++) {
				if (isset($employees[$i]['User'])) {
					$user = $this->Employee->User->findById($employees[$i]['User']['id']);
	
					$employees[$i]['User'] = $user['User'];
					$employees[$i]['User']['Unit'] = $user['Unit'];
					$employees[$i]['User']['Group'] = $user['Group'];
				}
			}
	
			// Copia as informacoes de aniversario
			foreach ($employees as $employee) {
				$entry = array();
				$entry['type'] = "employee";
				$entry['date'] = $employee['User']['birthdate'];
				$entry['id'] = $employee['Employee']['id'];
				$name = $employee['User']['name'];
				$entry['name'] = $name;
				$entry['nick'] = substr($name, 0, strpos($name,' '));
				$birthdays[]=$entry;
			}
			
			
			// Filter for present only employee from an organization
			$assistidos = $this->Assistido->query(
				'SELECT DISTINCT Assistido.id, Assistido.nome, Assistido.unit_id, Assistido.birthdate '.
				' FROM assistidos as Assistido'.
				' INNER JOIN units as Unit ON Assistido.unit_id = Unit.id'.
				' WHERE 1 = 1 '.$where.' AND MONTH(`Assistido`.birthdate) = '.$month
			);
			$assistidos_count = count($assistidos);
			for ($i=0; $i<$assistidos_count; $i++) {
				if (isset($assistidos[$i]['Assistido']['unit_id'])) {
					$unit = $this->Assistido->Unit->findById($assistidos[$i]['Assistido']['unit_id']);
					$assistidos[$i]['Unit'] = $unit['Unit'];
				}
	
			}
	
			// Copia as informacoes de aniversario
			foreach ($assistidos as $assistido) {
				$entry = array();
				$entry['type'] = "assistido";
				$entry['date'] = $assistido['Assistido']['birthdate'];
				$entry['id'] = $assistido['Assistido']['id'];
				$name = $assistido['Assistido']['nome'];
				$entry['name'] = $name;
				$entry['nick'] = substr($name, 0, strpos($name,' '));
				$birthdays[]=$entry;
			}
		}		
		$this->set(compact('events','prev','next','data','birthdays'));
	}

	function add() {
		$title = 'Cadastrar evento';
		$this->set('title', $title);
		$this->set('pageTitle', $title);

		$this->set('organizations', $this->Event->Organization->find('list'));
		$conditions = array();
		// Permissao: se pode visualizar todas as unidades
		$group = $this->othAuth->getData('group');
		$level =$group['level'];
		$unitUser = $this->othAuth->getData('unit');
		if ($level >= 100) {  // not system admin
			$conditions[] = array("organization_id"=>$unitUser['0']['Organization']['id']);
		}
		$fields = array('id','name');
		$calendars = $this->Calendar->find('list',array('conditions'=>$conditions, 'fields'=>$fields));
		$this->set('calendars', $calendars);
		
		if (!empty($this->data)) {
			// Validacao
			if($this->data["Event"]["title"] == null) {
				$_SESSION['mensagem']['error'][] = 'O campo Título é obrigatório.';
			}
			if($this->data["Event"]["headline"] == null) {
				$_SESSION['mensagem']['error'][] = 'O campo Título resumido é obrigatório.';
			}
			if($this->data["Event"]["date"] == null) {
				$_SESSION['mensagem']['error'][] = 'O campo Data é obrigatório.';
			}

			if (!(isset($_SESSION['mensagem']['error']))) {
				if ($this->Event->save($this->data)) {
					$_SESSION['mensagem']['success'][] = 'Evento cadastrado com sucesso!';
					$this->redirect('/events/view/'.$this->Event->getLastInsertId());
				} else {
					$_SESSION['mensagem']['error'][] = 'Erro ao tentar cadastrar o evento.';
				}
				$this->redirect('/events/');
			}
		}
	}

	function edit( $id=null) {
		if (!$id) $this->redirect('/events');
		$title = 'Editar evento';
		$this->set('title',$title);
		$this->set('pageTitle',$title);
		
		$this->set('organizations', $this->Event->Organization->find('list'));
		$conditions = array();
		// Permissao: se pode visualizar todas as unidades
		$group = $this->othAuth->getData('group');
		$level =$group['level'];
		$unitUser = $this->othAuth->getData('unit');
		if ($level >= 100) {  // not system admin
			$conditions[] = array("organization_id"=>$unitUser['0']['Organization']['id']);
		}
		$fields = array('id','name');
		$calendars = $this->Calendar->find('list',array('conditions'=>$conditions, 'fields'=>$fields));
		$this->set('calendars', $calendars);
		
		$this->Event->id = $id;
		if (empty($this->data)) {
			$this->data = $this->Event->read();
		} else {
			// Validacao
			if($this->data["Event"]["title"] == null) {
				$_SESSION['mensagem']['error'][] = 'O campo Título é obrigatório.';
			}
			if($this->data["Event"]["headline"] == null) {
				$_SESSION['mensagem']['error'][] = 'O campo Título resumido é obrigatório.';
			}
			if($this->data["Event"]["date"] == null) {
				$_SESSION['mensagem']['error'][] = 'O campo Data é obrigatório.';
			}
			
			if (!(isset($_SESSION['mensagem']['error']))) {
				if ($this->Event->save($this->data)) {
					$_SESSION['mensagem']['success'][] = 'Evento alterado com sucesso!';
				} else {
					$_SESSION['mensagem']['error'][] = 'Erro ao tentar alterar o evento.';
				}
				$this->redirect('/events/view/'.$id);
			}
			
		}
		$event = $this->Event->find(array('`Event`.id' => $id));
		$this->set('event', $event);
	}

	function delete($id) {
		if (!$id) $this->redirect('/events');
		if ($this->Event->del($id)) {
			$_SESSION['mensagem']['success'][] = 'Evento excluido com sucesso!';
		} else {
			$_SESSION['mensagem']['error'][] = 'Erro ao tentar excluir o evento.';
		}
		$this->redirect('/events');
	}

}